package com.example.weather2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.text.DateFormat;
import java.text.Normalizer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import data_model.DatabaseWeather;
import data_model.DateData;
import database.MyDBHandler;


import android.app.Activity;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity {
	ArrayList<DateData> arrDate=new ArrayList<DateData>();
	ArrayList<DatabaseWeather> arrDBWeather=new ArrayList<DatabaseWeather>();
	DateData d = new DateData();
	MyDBHandler db=new MyDBHandler(this);
	DatabaseWeather dbWea=new DatabaseWeather();
	
	String url = "http://api.wunderground.com/api/52245cd26b4d6a50/conditions/forecast7day/lang:VU/q/";
	//Call id ngay
    TextView tenTP;
    TextView ngayThangNam;
    TextView thuCell_1;
    TextView ngayThangCell_1;
    TextView thuCell_2;
    TextView ngayThangCell_2;
    TextView thuCell_3;
    TextView ngayThangCell_3;
    TextView thuCell_4;
    TextView ngayThangCell_4;
    TextView thuCell_5;
    TextView ngayThangCell_5;
    TextView thuCell_6;
    TextView ngayThangCell_6;
    //Call id Nhiet do
    TextView nhietDoHienTai;
    TextView nhietDoHienTaiMax;
    TextView nhietDoHienTaiMin;
    TextView kieutroi;
    TextView realFeel;
    TextView nhietDoMax_1;
    TextView nhietDoMin_1;
    TextView nhietDoMax_2;
    TextView nhietDoMin_2;
    TextView nhietDoMax_3;
    TextView nhietDoMin_3;
    TextView nhietDoMax_4;
    TextView nhietDoMin_4;
    TextView nhietDoMax_5;
    TextView nhietDoMin_5;
    TextView nhietDoMax_6;
    TextView nhietDoMin_6;
    //call id avehumidity
    TextView avehumidity_1;
    TextView avehumidity_2;
    TextView avehumidity_3;
    TextView avehumidity_4;
    TextView avehumidity_5;
    TextView avehumidity_6;
    //call id UV
    TextView UV;
    //call id Imageview
    ImageView iconHienTai;
    //call id do am va gio
    TextView doAm;
    TextView tocDoGio;
    TextView update;
    AutoCompleteTextView edtInput;
    ImageView img_2;
	ImageView img_3;
	ImageView img_4;
	ImageView img_5;
	ImageView img_6;
	ImageView img_7;
    private String time="";
    private String city="";
    String cityCode="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
		//Full Screen
		requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        setContentView(R.layout.layout_main);
        private ConnectivityManager connect;
      //Call id ngay
        tenTP=(TextView)findViewById(R.id.txt_tenTP);
        ngayThangNam=(TextView)findViewById(R.id.txt_date);
        thuCell_1=(TextView)findViewById(R.id.txt_cell_1_thu);
        ngayThangCell_1=(TextView)findViewById(R.id.txt_cell_1_ngay);
        thuCell_2=(TextView)findViewById(R.id.txt_cell_2_thu);
        ngayThangCell_2=(TextView)findViewById(R.id.txt_cell_2_ngay);
        thuCell_3=(TextView)findViewById(R.id.txt_cell_3_thu);
        ngayThangCell_3=(TextView)findViewById(R.id.txt_cell_3_ngay);
        thuCell_4=(TextView)findViewById(R.id.txt_cell_4_thu);
        ngayThangCell_4=(TextView)findViewById(R.id.txt_cell_4_ngay);
        thuCell_5=(TextView)findViewById(R.id.txt_cell_5_thu);
        ngayThangCell_5=(TextView)findViewById(R.id.txt_cell_5_ngay);
        thuCell_6=(TextView)findViewById(R.id.txt_cell_6_thu);
        ngayThangCell_6=(TextView)findViewById(R.id.txt_cell_6_ngay);
        
        //Call id Nhiet do
        nhietDoHienTai=(TextView)findViewById(R.id.txt_nhietDo);
        nhietDoHienTaiMax=(TextView)findViewById(R.id.txt_nhietDo_max);
        nhietDoHienTaiMin=(TextView)findViewById(R.id.txt_nhietDo_min);
        kieutroi=(TextView)findViewById(R.id.txt_kieutroi);
        realFeel=(TextView)findViewById(R.id.txt_realFeel);
        nhietDoMax_1=(TextView)findViewById(R.id.txt_cell_1_max);
        nhietDoMin_1=(TextView)findViewById(R.id.txt_cell_1_min);
        nhietDoMax_2=(TextView)findViewById(R.id.txt_cell_2_max);
        nhietDoMin_2=(TextView)findViewById(R.id.txt_cell_2_min);
        nhietDoMax_3=(TextView)findViewById(R.id.txt_cell_3_max);
        nhietDoMin_3=(TextView)findViewById(R.id.txt_cell_3_min);
        nhietDoMax_4=(TextView)findViewById(R.id.txt_cell_4_max);
        nhietDoMin_4=(TextView)findViewById(R.id.txt_cell_4_min);
        nhietDoMax_5=(TextView)findViewById(R.id.txt_cell_5_max);
        nhietDoMin_5=(TextView)findViewById(R.id.txt_cell_5_min);
        nhietDoMax_6=(TextView)findViewById(R.id.txt_cell_6_max);
        nhietDoMin_6=(TextView)findViewById(R.id.txt_cell_6_min);
        
        //call id avehumidity
        avehumidity_1=(TextView)findViewById(R.id.txt_cell_1_avehumidity);
        avehumidity_2=(TextView)findViewById(R.id.txt_cell_2_avehumidity);
        avehumidity_3=(TextView)findViewById(R.id.txt_cell_3_avehumidity);
        avehumidity_4=(TextView)findViewById(R.id.txt_cell_4_avehumidity);
        avehumidity_5=(TextView)findViewById(R.id.txt_cell_5_avehumidity);
        avehumidity_6=(TextView)findViewById(R.id.txt_cell_6_avehumidity);
        update=(TextView)findViewById(R.id.txt_update);
        //call id UV
        UV=(TextView)findViewById(R.id.txt_UV);
        //call id Imageview
        iconHienTai=(ImageView)findViewById(R.id.img_iconWeather);
        //call id do am va gio
        doAm=(TextView)findViewById(R.id.txt_humidity);
        tocDoGio=(TextView)findViewById(R.id.txt_windy);
        //call id of search
        //db.deleteTable();
        showWeather();
        //updateCity();
		//Toast.makeText(getBaseContext(), "Đã cập nhật!", Toast.LENGTH_LONG).show();
        edtInput=(AutoCompleteTextView)findViewById(R.id.edtInput);
        ImageButton btnSearch=(ImageButton)findViewById(R.id.img_btn_search);
        ImageButton btnUpdate=(ImageButton)findViewById(R.id.btn_update);
        edtInput.setThreshold(1);
        edtInput.setAdapter(ini_Autocomplete_ThanhPho());
   
        btnSearch.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String str=edtInput.getText().toString();
				String mUrl=str.replace(" ", "_");
				mUrl=parse_Url(mUrl);
				cityCode=mUrl;
				url+=mUrl+".xml";
				Log.i("test", url);
				//Toast.makeText(MainActivity.this, url, 15).show();
				try {
					loadData();
					
				}catch (Exception e) {
				//	Toast.makeText(MainActivity.this, "Dang phat trien", 7).show();
				}
				//dbWea.set_city(city);
				//Add_City();
				edtInput.setText("");
				edtInput.requestFocus();
				url = "http://api.wunderground.com/api/52245cd26b4d6a50/conditions/forecast7day/lang:VU/q/";
			}
		});
   
        btnUpdate.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				updateCity();
				Toast.makeText(getBaseContext(), "Đã cập nhật!", Toast.LENGTH_LONG).show();
			}
		});
    }
    //Ham xu ly ket qua tra ve tu api vaf doc the
    public void loadData(){

        arrDate=new ArrayList<DateData>();
    	//arrDate.clear();
        String input = readDataFromWS();
       
		try {
			XmlPullParserFactory fc = XmlPullParserFactory.newInstance();
			XmlPullParser parser = fc.newPullParser();

			parser.setInput(new StringReader(input));
			
			int eventType = -1;
			String nodeName;
			boolean found_simple = false;
			boolean found = false;
			boolean found_h = false;
			boolean found_l = false;
			
			while (eventType != XmlPullParser.END_DOCUMENT)// Duyet cho den het
			{
				//Log.i("test", input);
				eventType = parser.next();// bắt đầu duyệt để
				switch (eventType) {
				case XmlPullParser.START_DOCUMENT:
					break;
				case XmlPullParser.END_DOCUMENT:
					break;
				case XmlPullParser.START_TAG: // là tag mở 
					nodeName = parser.getName();
					Log.i("test1","......"+nodeName);
					if (nodeName.equals("current_observation")) {// Kiem tra Tag can lay 
						found=true;
					}
					if(nodeName.equals("simpleforecast")){
						found_simple = true;
						Log.i("test1", "true");
					}
					if(nodeName.equals("temp_c")){
						String str=parser.nextText();
						nhietDoHienTai.setText(str+"°C");
						dbWea.set_nhietdoht(str);
					}
					if(nodeName.equals("feelslike_c")){
						String str=parser.nextText();
						realFeel.setText(str+"°C");
						dbWea.setRealFeel(str);
					}
					if(nodeName.equals("relative_humidity")){
						String str=parser.nextText();
						doAm.setText(str);
						dbWea.set_doam(str);
					}
					if(nodeName.equals("UV")){
						String str=parser.nextText();
						dbWea.set_uv(str);
						int uv=Integer.parseInt(str);
						ktraUV(uv);
					}
					if(nodeName.equals("wind_kph")){
						String str=parser.nextText();
						tocDoGio.setText(str+" Kph");
						dbWea.set_tocdogio(str);
					}
					if(nodeName.equals("weather")){
						String str=parser.nextText();
						kieutroi.setText(str);
						dbWea.set_kieutroi_1(str);
						kieutroi(str);
						
					}
					if (nodeName.equals("display_location")) {// Kiem tra Tag can lay 
						found=true;
					}
					if (found_simple && nodeName.equals("forecastday") ) {// Kiem tra Tag can lay 
						found=true;
					}
					if (nodeName.equals("high") && found) {// Kiem tra Tag nhiệt độ cao nhất
						found_h=true;
						//Log.i("test", "High Có");
					}
					if (nodeName.equals("low") && found) {// Kiem tra Tag can lay 
						found_l=true;
						//Log.i("test", "Low Có");
					}
					if(nodeName.equals("celsius") && found_h){
						String str=parser.nextText();
						d.set_maxTemperature(str);
					}
					if(nodeName.equals("celsius") && found_l){
						String str=parser.nextText();
						d.set_minTemperature(str);
					}
					if(nodeName.equals("city") && found){
						String str=parser.nextText();
						tenTP.setText(str);
						dbWea.set_city(str);
					}
					if(nodeName.equals("weekday_short") && found){
						String str=parser.nextText();
						//dbWea.set_thuht(str);
						if(str.contains("Chủ Nhật")){
							str="CN";
							d.set_thu(str);
						}
						else{
							d.set_thu(str);
						}
						//Log.i("test", str);
					}
					if(nodeName.equals("day") && found){
						String str=parser.nextText();
						d.set_day(str);
						
					}
					if(nodeName.equals("month") && found){
						String str=parser.nextText();
						d.set_month(str);
						
					}
					if(nodeName.equals("avehumidity") && found){
						String str=parser.nextText();
						d.set_avehumidity(str);
					}
					if(nodeName.equals("conditions")&& found){
						String str=parser.nextText();
						d.set_conditions(str);
						//Log.i("test", str);
					}
					
					break;
				case XmlPullParser.END_TAG:// là tag đóng
					nodeName = parser.getName();
					if (nodeName.equals("current_observation")) {// Kiem tra Tag can lay 
						found=false;
					}
					
					if (nodeName.equals("display_location")) {// Kiem tra Tag can lay 
						found=false;
					}
					if(nodeName.equals("simpleforecast")){
						found_simple = false;
						//Log.i("test1","false");
					}	
					if (found_simple && nodeName.equals("forecastday")) {// Kiem tra Tag can lay 
						found=false;
						arrDate.add(d);
						d=new DateData();
						Log.v("test","soluong arr:"+arrDate.size());
					}
					if (nodeName.equals("high")) {
						found_h=false;
					}
					if (nodeName.equals("low")) {
						found_l=false;
					}
					break;
				}
				
			} 
			Log.i("test","sl:"+arrDate.size()+"");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		url = "http://api.wunderground.com/api/52245cd26b4d6a50/conditions/forecast7day/lang:VU/q/";
		//Toast.makeText(this, arrDate.size()+"", 30).show();
		for (int i = 0; i < arrDate.size(); i++) {
			//Log.w("test", arrDate.get(i).get_maxTemperature()+"-"+arrDate.get(i).get_minTemperature());
			if(i==0){
				String thu=arrDate.get(i).get_thu();
				String ngay=arrDate.get(i).get_day();
				String thang=arrDate.get(i).get_month();
				String max=arrDate.get(i).get_maxTemperature()+"°";
				String min=arrDate.get(i).get_minTemperature()+"°";
				ngayThangNam.setText(thu+", "+ngay+" Tháng "+thang);
				nhietDoHienTaiMax.setText(max);
				nhietDoHienTaiMin.setText(min);
				dbWea.set_thuht(thu);
				dbWea.set_ngayht(ngay);
				dbWea.set_thanght(thang);
				dbWea.set_nhietdocaonhat_1(max);
				dbWea.set_nhietdothapnhat_1(min);
			}
			if(i==1){
				String thu=arrDate.get(i).get_thu();
				String ngay=arrDate.get(i).get_day();
				String thang=arrDate.get(i).get_month();
				String max=arrDate.get(i).get_maxTemperature()+"°/";
				String min=arrDate.get(i).get_minTemperature()+"°";
				String kieutroi=arrDate.get(i).get_conditions();
				String avehumidity=arrDate.get(i).get_avehumidity();
				thuCell_1.setText(thu);
				ngayThangCell_1.setText(ngay+"/"+thang);
				nhietDoMax_1.setText(max);
				nhietDoMin_1.setText(min);
				avehumidity_1.setText(avehumidity+"%");
				//-------------------
				dbWea.set_thu_2(thu);
				dbWea.set_ngay_2(ngay);
				dbWea.set_thang_2(thang);
				dbWea.set_kieutroi_2(kieutroi);
				dbWea.set_nhietdocaonhat_2(max);
				dbWea.set_nhietdothapnhat_2(min);
				dbWea.set_doam_2(avehumidity);
			}
			if(i==2){
				String thu=arrDate.get(i).get_thu();
				String ngay=arrDate.get(i).get_day();
				String thang=arrDate.get(i).get_month();
				String max=arrDate.get(i).get_maxTemperature()+"°/";
				String min=arrDate.get(i).get_minTemperature()+"°";
				String kieutroi=arrDate.get(i).get_conditions();
				String avehumidity=arrDate.get(i).get_avehumidity();
				thuCell_2.setText(thu);
				ngayThangCell_2.setText(ngay+"/"+thang);
				nhietDoMax_2.setText(max);
				nhietDoMin_2.setText(min);
				avehumidity_2.setText(avehumidity+"%");
				//-------------------
				dbWea.set_thu_3(thu);
				dbWea.set_ngay_3(ngay);
				dbWea.set_thang_3(thang);
				dbWea.set_kieutroi_3(kieutroi);
				dbWea.set_nhietdocaonhat_3(max);
				dbWea.set_nhietdothapnhat_3(min);
				dbWea.set_doam_3(avehumidity);
			}
			if(i==3){
				String thu=arrDate.get(i).get_thu();
				String ngay=arrDate.get(i).get_day();
				String thang=arrDate.get(i).get_month();
				String max=arrDate.get(i).get_maxTemperature()+"°/";
				String min=arrDate.get(i).get_minTemperature()+"°";
				String kieutroi=arrDate.get(i).get_conditions();
				String avehumidity=arrDate.get(i).get_avehumidity();
				thuCell_3.setText(thu);
				ngayThangCell_3.setText(ngay+"/"+thang);
				nhietDoMax_3.setText(max);
				nhietDoMin_3.setText(min);
				avehumidity_3.setText(avehumidity+"%");
				//-------------------
				dbWea.set_thu_4(thu);
				dbWea.set_ngay_4(ngay);
				dbWea.set_thang_4(thang);
				dbWea.set_kieutroi_4(kieutroi);
				dbWea.set_nhietdocaonhat_4(max);
				dbWea.set_nhietdothapnhat_4(min);
				dbWea.set_doam_4(avehumidity);
			}
			if(i==4){
				String thu=arrDate.get(i).get_thu();
				String ngay=arrDate.get(i).get_day();
				String thang=arrDate.get(i).get_month();
				String max=arrDate.get(i).get_maxTemperature()+"°/";
				String min=arrDate.get(i).get_minTemperature()+"°";
				String kieutroi=arrDate.get(i).get_conditions();
				String avehumidity=arrDate.get(i).get_avehumidity();
				thuCell_4.setText(thu);
				ngayThangCell_4.setText(ngay+"/"+thang);
				nhietDoMax_4.setText(max);
				nhietDoMin_4.setText(min);
				avehumidity_4.setText(avehumidity+"%");
				//-------------------
				dbWea.set_thu_5(thu);
				dbWea.set_ngay_5(ngay);
				dbWea.set_thang_5(thang);
				dbWea.set_kieutroi_5(kieutroi);
				dbWea.set_nhietdocaonhat_5(max);
				dbWea.set_nhietdothapnhat_5(min);
				dbWea.set_doam_5(avehumidity);
			}
			if(i==5){
				String thu=arrDate.get(i).get_thu();
				String ngay=arrDate.get(i).get_day();
				String thang=arrDate.get(i).get_month();
				String max=arrDate.get(i).get_maxTemperature()+"°/";
				String min=arrDate.get(i).get_minTemperature()+"°";
				String kieutroi=arrDate.get(i).get_conditions();
				String avehumidity=arrDate.get(i).get_avehumidity();
				thuCell_5.setText(thu);
				ngayThangCell_5.setText(ngay+"/"+thang);
				nhietDoMax_5.setText(max);
				nhietDoMin_5.setText(min);
				avehumidity_5.setText(avehumidity+"%");
				//-------------------
				dbWea.set_thu_6(thu);
				dbWea.set_ngay_6(ngay);
				dbWea.set_thang_6(thang);
				dbWea.set_kieutroi_6(kieutroi);
				dbWea.set_nhietdocaonhat_6(max);
				dbWea.set_nhietdothapnhat_6(min);
				dbWea.set_doam_6(avehumidity);
			}
			if(i==6){
				String thu=arrDate.get(i).get_thu();
				String ngay=arrDate.get(i).get_day();
				String thang=arrDate.get(i).get_month();
				String max=arrDate.get(i).get_maxTemperature()+"°/";
				String min=arrDate.get(i).get_minTemperature()+"°";
				String kieutroi=arrDate.get(i).get_conditions();
				String avehumidity=arrDate.get(i).get_avehumidity();
				thuCell_6.setText(thu);
				ngayThangCell_6.setText(ngay+"/"+thang);
				nhietDoMax_6.setText(max);
				nhietDoMin_6.setText(min);
				avehumidity_6.setText(avehumidity+"%");
				//-------------------
				dbWea.set_thu_7(thu);
				dbWea.set_ngay_7(ngay);
				dbWea.set_thang_7(thang);
				dbWea.set_kieutroi_7(kieutroi);
				dbWea.set_nhietdocaonhat_7(max);
				dbWea.set_nhietdothapnhat_7(min);
				dbWea.set_doam_7(avehumidity);
			}
		}
		DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
		Calendar cal = Calendar.getInstance();
		time=(dateFormat.format(cal.getTime()));
		update.setText("Đã cập nhật: "+time);
		dbWea.set_timer(time);
		dbWea.set_cityCode(cityCode);
		if(arrDate.size()!=0){
			db.deleteCity();
			db.addCity(dbWea);
		}
		else{
			Toast.makeText(this, "Khu vực chỉ cập nhật hiện thời chưa có dữ liệu các ngày kế tiếp. Vì vậy khu vực sẽ không được lưu vào DB (Vẫn đang phát triển)", 120).show();
		}
		kindOfWeather();
		arrDate.clear();
    }
    
    //set hinh anh kieu thoi tiet
    public void kindOfWeather(){
    String str="";
    	//ImageView img_1=(ImageView)findViewById(R.id.img_iconWeather);
    	img_2=(ImageView)findViewById(R.id.img_cell_1_image);
    	img_3=(ImageView)findViewById(R.id.img_cell_2_image);
    	img_4=(ImageView)findViewById(R.id.img_cell_3_image);
    	img_5=(ImageView)findViewById(R.id.img_cell_4_image);
    	img_6=(ImageView)findViewById(R.id.img_cell_5_image);
    	img_7=(ImageView)findViewById(R.id.img_cell_6_image);
    	ArrayList<String> arrStr=new ArrayList<String>();
    	int resid = 0 ;
    	for (int i = 0; i < arrDate.size(); i++) {

    		str=arrDate.get(i).get_conditions();
    		//Log.w("test",str);
    		if(str.contains("Có Thể Có Mưa")){
    			resid=R.drawable.mua;
    			arrStr.add(resid+"");
    		}
    		if(str.contains("Có Dông")){
    			resid=R.drawable.co_dong;
    			arrStr.add(resid+"");
    		}
    		if(str.contains("Hơi Có Mây")){
    			resid=R.drawable.sun_cloudy;
    			arrStr.add(resid+"");
    		}
    		if(str.contains("Trời Ðẹp")){
    			resid=R.drawable.sun;
    			arrStr.add(resid+"");
    		}
    		if(str.contains("Có Thể Có Dông")){
    			resid=R.drawable.ico_rain;
    			arrStr.add(resid+"");
    		}
    		
		}
    	//img_1.setImageResource(Integer.parseInt(arrStr.get(0)));
    	img_2.setImageResource(Integer.parseInt(arrStr.get(1)));
    	img_3.setImageResource(Integer.parseInt(arrStr.get(2)));
    	img_4.setImageResource(Integer.parseInt(arrStr.get(3)));
    	img_5.setImageResource(Integer.parseInt(arrStr.get(4)));
    	img_6.setImageResource(Integer.parseInt(arrStr.get(5)));
    	img_7.setImageResource(Integer.parseInt(arrStr.get(6)));
    	arrStr.clear();
    }
    

  //function to show data weather from database to screen
  	public void showWeather()
  	{
  		arrDBWeather=db.findCity();
  		
          for (int i = 0; i < arrDBWeather.size(); i++) {
          	DatabaseWeather d=arrDBWeather.get(i);
          	String tiaUV=d.get_uv();
          	String str1=d.get_kieutroi_1();
          	String str2=d.get_kieutroi_2();
          	String str3=d.get_kieutroi_3();
          	String str4=d.get_kieutroi_4();
          	String str5=d.get_kieutroi_5();
          	String str6=d.get_kieutroi_6();
          	String str7=d.get_kieutroi_7();
          	
          	update.setText("Đã cập nhật: "+d.get_timer());
          	tenTP.setText(d.get_city());
          	ngayThangNam.setText(d.get_thuht()+", "+d.get_ngayht()+" Tháng "+d.get_thanght());
          	nhietDoHienTai.setText(d.get_nhietdoht()+"°C");
          	nhietDoHienTaiMax.setText(d.get_nhietdocaonhat_1());
          	nhietDoHienTaiMin.setText(d.get_nhietdothapnhat_1());
          	kieutroi.setText(d.get_kieutroi_1());
          	realFeel.setText(d.getRealFeel()+"°C");
          	doAm.setText(d.get_doam());
          	tocDoGio.setText(d.get_tocdogio());
          	int uv=Integer.parseInt(tiaUV);
  			ktraUV(uv);
  			//set image kieu troi
  			kieutroi(str1);
  			thuCell_1.setText(d.get_thu_2());
  			ngayThangCell_1.setText(d.get_ngay_2()+"/"+d.get_thang_2());
  			nhietDoMax_1.setText(d.get_nhietdocaonhat_2());
  			nhietDoMin_1.setText(d.get_nhietdothapnhat_2());
  			avehumidity_1.setText(d.get_doam_2()+"%");
  			//--------------------------
  			thuCell_2.setText(d.get_thu_3());
  			ngayThangCell_2.setText(d.get_ngay_3()+"/"+d.get_thang_3());
  			nhietDoMax_2.setText(d.get_nhietdocaonhat_3());
  			nhietDoMin_2.setText(d.get_nhietdothapnhat_3());
  			avehumidity_2.setText(d.get_doam_3()+"%");
  			//--------------------------
  			thuCell_3.setText(d.get_thu_4());
  			ngayThangCell_3.setText(d.get_ngay_4()+"/"+d.get_thang_4());
  			nhietDoMax_3.setText(d.get_nhietdocaonhat_4());
  			nhietDoMin_3.setText(d.get_nhietdothapnhat_4());
  			avehumidity_3.setText(d.get_doam_4()+"%");
  			//--------------------------
  			thuCell_4.setText(d.get_thu_5());
  			ngayThangCell_4.setText(d.get_ngay_5()+"/"+d.get_thang_5());
  			nhietDoMax_4.setText(d.get_nhietdocaonhat_5());
  			nhietDoMin_4.setText(d.get_nhietdothapnhat_5());
  			avehumidity_4.setText(d.get_doam_5()+"%");
  			//--------------------------
  			thuCell_5.setText(d.get_thu_6());
  			ngayThangCell_5.setText(d.get_ngay_6()+"/"+d.get_thang_6());
  			nhietDoMax_5.setText(d.get_nhietdocaonhat_6());
  			nhietDoMin_5.setText(d.get_nhietdothapnhat_6());
  			avehumidity_5.setText(d.get_doam_6()+"%");
  			//--------------------------
  			thuCell_6.setText(d.get_thu_7());
  			ngayThangCell_6.setText(d.get_ngay_7()+"/"+d.get_thang_7());
  			nhietDoMax_6.setText(d.get_nhietdocaonhat_7());
  			nhietDoMin_6.setText(d.get_nhietdothapnhat_7());
  			avehumidity_6.setText(d.get_doam_7()+"%");
  			kieutroiDatabase();
  		}
          arrDBWeather.clear();
  	}
  //Kiem tra kieu troi tu database
  	public void kieutroiDatabase(){
  		img_2=(ImageView)findViewById(R.id.img_cell_1_image);
      	img_3=(ImageView)findViewById(R.id.img_cell_2_image);
      	img_4=(ImageView)findViewById(R.id.img_cell_3_image);
      	img_5=(ImageView)findViewById(R.id.img_cell_4_image);
      	img_6=(ImageView)findViewById(R.id.img_cell_5_image);
      	img_7=(ImageView)findViewById(R.id.img_cell_6_image);    
      	
      	img_2.setImageResource(Integer.parseInt(resID(arrDBWeather.get(0).get_kieutroi_2())));
      	img_3.setImageResource(Integer.parseInt(resID(arrDBWeather.get(0).get_kieutroi_3())));
      	img_4.setImageResource(Integer.parseInt(resID(arrDBWeather.get(0).get_kieutroi_4())));
      	img_5.setImageResource(Integer.parseInt(resID(arrDBWeather.get(0).get_kieutroi_5())));
      	img_6.setImageResource(Integer.parseInt(resID(arrDBWeather.get(0).get_kieutroi_6())));
      	img_7.setImageResource(Integer.parseInt(resID(arrDBWeather.get(0).get_kieutroi_7())));
      	
  	}
      public String resID(String str){
      	int resid = 0 ;
      	if(str.contains("Có Thể Có Mưa")){
  			resid=R.drawable.mua;
  			
  		}
  		if(str.contains("Có Dông")){
  			resid=R.drawable.co_dong;
  			
  		}
  		if(str.contains("Hơi Có Mây")){
  			resid=R.drawable.sun_cloudy;
  			
  		}
  		if(str.contains("Trời Ðẹp")){
  			resid=R.drawable.sun;
  			
  		}
  		if(str.contains("Có Thể Có Dông")){
  			resid=R.drawable.ico_rain;
  			
  		}
      	return resid+"";
      }

  	//Ham xu ly ket qua UV de dua ra loi khuyen
  	public void ktraUV(int uv){
		if((uv==0 || uv>0 ||uv<0) && (uv<3)){
			UV.setText("Thấp");
			//Toast.makeText(getBaseContext(), "Thích hợp cho bạn vui chơi không có ảnh hưởng từ UV!", 5).show();
		}
		if((uv==3 || uv>3) && (uv<6)){
			UV.setText("Trung bình");
		}
		if((uv==6 || uv>6) && (uv<8)){
			UV.setText("Cao");
		}
		if((uv==8 || uv>8) && (uv<11)){
			UV.setText("Rất cao");
		}
		if(uv==11 || uv>11){
			UV.setText("Cực cao");
			Toast.makeText(getBaseContext(), "Bạn hãy hạn chế tiếp xúc trực tiếp với nắng!", Toast.LENGTH_LONG).show();
		}
	}
  	
  	//Ham kiem tra kieu thoi tiet de set hinh anh cho nhung ngay ke tiep
  	public void kieutroi(String str){
		if(str.contains("Có Thể Có Mưa")){
			//set image resources
		}
		if(str.contains("Có Dông")){
			//set image resources
		}
		if(str.contains("Hơi Có Mây")){
			//set image resources
		}
		if(str.contains("Trời Ðẹp")){
			//set image resources
		}
		if(str.contains("Có Thể Có Dông")){
			//set image resources
		}
		if(str.contains("Mây Âm U")){
			//set image resources
		}
	}
  	//Ham Khoi Tao Adapter cho Autocomplete
  	public ArrayAdapter<CharSequence> ini_Autocomplete_ThanhPho(){
  		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(MainActivity.this,R.array.location,android.R.layout.simple_spinner_dropdown_item);
        return adapter;
  	}
  //Ham xu ly input City nhap vao phu hop voi key search api
  	public String parse_Url(String mUrl){
  		String[] arrlocation = null;
  		arrlocation = getResources().getStringArray(R.array.location);
  		for (String s : arrlocation) {
			String temp = Normalizer.normalize(mUrl.toLowerCase().trim(), Normalizer.Form.NFD);
	        Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
	        mUrl = pattern.matcher(temp).replaceAll("").replaceAll("Đ", "D").replace("đ", "d");
	       // Log.i("test","string murl"+ mUrl);
	        temp = Normalizer.normalize(s.toLowerCase().trim(), Normalizer.Form.NFD);
	        pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
	        s = pattern.matcher(temp).replaceAll("").replaceAll("Đ", "D").replace("đ", "d");
	        //Log.i("test","string truoc"+ s);
			if(mUrl.contains(s) || 
					s.contains(mUrl) || 
					
					mUrl.contains(s.replaceAll(" ","")) || s.contains(mUrl.replaceAll(" ","")) ||
					mUrl.replaceAll(" ","").contains(s) || s.replaceAll(" ","").contains(mUrl) ||
					mUrl.replaceAll(" ","").contains(s.replaceAll(" ","")) || 
					s.replaceAll(" ","").contains(mUrl.replaceAll(" ","")) || 
					
					mUrl.contains(s.replaceAll("_","")) || s.contains(mUrl.replaceAll("_","")) ||
					mUrl.replaceAll("_","").contains(s) || s.replaceAll("_","").contains(mUrl) ||
					mUrl.replaceAll("_","").contains(s.replaceAll("_","")) || 
					s.replaceAll("_","").contains(mUrl.replaceAll("_",""))
					){
				return s.replaceAll(" ", "_");
			}
		}
  		return mUrl;
  	}
  	
  //Hàm update dữ liệu mới từ internet thay cho dữ liệu trong database của 1 thành phố
  	public void updateCity(){
  		arrDBWeather=db.findCity();
  		Log.v("test", arrDBWeather.get(0).get_cityCode()+"");
  		String str =arrDBWeather.get(0).get_cityCode();
  		String mUrl=str.replace(" ", "_");
		mUrl=parse_Url(mUrl);
		cityCode=mUrl;
		url+=mUrl+".xml";
		Log.v("test", url);
		try{
			loadData();
		}
		catch(Exception e){
			
		}
		edtInput.setText("");
		edtInput.requestFocus();
		url = "http://api.wunderground.com/api/52245cd26b4d6a50/conditions/forecast7day/lang:VU/q/";
  	}
	
	public void checkingInternet() {

		connect = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		// enableWifi =
		// conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
		if (isOnline()){
			Toast.makeText(getApplicationContext(), "Online ",Toast.LENGTH_SHORT).show();
		} 
		else {
			Toast.makeText(getApplicationContext(), "Offline ",Toast.LENGTH_SHORT).show();
			Intent intent = new Intent(android.provider.Settings.ACTION_NETWORK_OPERATOR_SETTINGS);startActivityForResult(intent, RESULT_CANCELED);
		}
		
	}
  //funtion Check online
  	public boolean isOnline()
  	{
  		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  		NetworkInfo netInfo = cm.getActiveNetworkInfo();
  		if (netInfo != null && netInfo.isConnectedOrConnecting()) 
  		{
  			return true;
  		}
  		return false;
  	}
  	//Ham ket noi den API
  	public String readDataFromWS() {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		try {
			HttpResponse response = client.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} else {
				Log.e("test", "Failed to download file");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return builder.toString();
	}
}
